﻿#include "filemonitor.h"

FileMonitor::FileMonitor(QObject *parent) : QObject(parent)
{
    timer = new QTimer(this);
    timer->setInterval(60 * 1000);
    connect(timer,&QTimer::timeout,this,&FileMonitor::updateTarget);
}

void FileMonitor::startMonitor(bool flag)
{
    if(flag)
    {
        generateTarget();
        timer->start(); // 1分钟
        emit monitoring(flag);
    }
    else
    {
        timer->stop();
        emit monitoring(flag);
    }
}

void FileMonitor::generateTarget()
{
    if(!targetList.isEmpty())
        targetList.clear();

    QSqlQuery query;
    query.exec(QString("select target from %1").arg(TD_MONITOR));
    while(query.next())
    {
        QString target=query.value("target").toString();
        targetList.append(target);

        uint time_stamp=sp_getTimestampByFile(target);
        targetTable.insert(target,time_stamp);
    }
}

void FileMonitor::updateTarget()
{
    if(targetList.isEmpty())
        return;

    if(!activityList.isEmpty())
        activityList.clear();

    foreach (QString target, targetList) {
        uint time_stamp=sp_getTimestampByFile(target);
        if(time_stamp > targetTable.value(target))
            activityList.append(target);
        targetTable.insert(target,time_stamp);
    }

    if(!activityList.isEmpty())
        emit fileChanged(activityList);
}
